package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理")
public class DishController
{
    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate  redisTemplate;

    @ApiOperation("菜品添加")
    @PostMapping
    @CacheEvict(cacheNames = "dish_" , key = "dishDTO.categoryId")
    public Result add(@RequestBody DishDTO dishDTO){
        log.info("菜品添加,{}", dishDTO);
        dishService.add(dishDTO);
        return Result.success();
    }

    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result find (DishPageQueryDTO  dishPageQueryDTO ){
        log.info("员工分页查询{}", dishPageQueryDTO);
        return Result.success(dishService.find(dishPageQueryDTO));
    }

    @ApiOperation("菜品id查询")
    @GetMapping("{id}")
    public Result<DishVO> findById (@PathVariable Long id ){
        log.info("员工分页查询{}", id);
        return Result.success(dishService.findById(id));
    }

    @ApiOperation("分类id查询菜品")
    @GetMapping("list")
    public Result findByCategoryId ( Long categoryId ){
        log.info("分类id查询菜品{}", categoryId);
        String key="dish_"+categoryId;

        List<DishVO> dishVOS = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(dishVOS!=null && dishVOS.size()>0){
            return Result.success(dishVOS);
        }
        dishVOS = dishService.findByCategoryId(categoryId);
        redisTemplate.opsForValue().set(key,dishVOS);

        return Result.success(dishVOS);
    }

    @ApiOperation("删除菜品")
    @DeleteMapping
    @CacheEvict(cacheNames = "dish_" , allEntries = true)
    public Result delete (@RequestParam List<Long> ids){
        dishService.delete(ids);
        return Result.success();
    }

    @ApiOperation("菜品修改")
    @PutMapping
    @CacheEvict(cacheNames = "dish_" , allEntries = true)
    public Result update (@RequestBody DishDTO dishDTO){
        dishService.updateWithFlavor(dishDTO);
        return Result.success();
    }
}
